package org.uned.agonzalo16.bitacora.service.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.uned.agonzalo16.bitacora.domain.User;
import org.uned.agonzalo16.bitacora.domain.UserType;

@SuppressWarnings("serial")
public class AuthenticatedUser implements UserDetails {

	private final Long id;
	private final String username;
	private final String password;
	private final boolean active;
	private final int type;

	public AuthenticatedUser(User user) {
		id = user.getId();
		username = user.getUsername();
		password = user.getPassword();
		active = user.isActive();
		type = user.getType();
	}

	public Long getId() {
		return id;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> result = new ArrayList<GrantedAuthority>();

		if (UserType.ADMIN.getType().equals(type)) {
			result.add(new SimpleGrantedAuthority(AppRoles.ADMIN.name()));
		}
		if (UserType.CONTRIBUTOR.getType().equals(type)) {
			result.add(new SimpleGrantedAuthority(AppRoles.CONTRIBUTOR.name()));
		}
		if (UserType.VISITOR.getType().equals(type)) {
			result.add(new SimpleGrantedAuthority(AppRoles.VISITOR.name()));
		}
		return result;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return active;
	}

	@Override
	public boolean isAccountNonLocked() {
		return active;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return active;
	}

	@Override
	public boolean isEnabled() {
		return active;
	}

}
